<?php
declare (strict_types=1);

namespace app\common\controller;

use app\common\model\Account;
use app\common\model\Relation;

class Bonus
{
    /**
     * 2团队收益/3平级收益
     */
    public static function teamBonus($uid, $amount): bool|string
    {
        try {
            $list = Relation::hasWhere('user', function ($query) {
                $query->where('level_id', '>', 0)->where(['is_active' => 2]);
            })->where(['new_uid' => $uid])->order('algebra asc')->select();
            if (!$list->isEmpty()) {
                $now_level_id = 0;
                $now_tp = 0;
                $now_bonus = 0;
                $flat_grade = 0;
                foreach ($list as $item) {
                    if ($item->user->level_id > $now_level_id) {
                        $tp = $item->user->level->tp;
                        $real_amount = round($amount * ($tp - $now_tp), 2);
                        Account::bonusEntry($item->uid, $real_amount, '团队收益', $uid, 2);
                        $now_level_id = $item->user->level_id;
                        $now_tp = $tp;
                        $now_bonus = $real_amount;
                        $flat_grade = 0;
                    } elseif ($item->user->level_id == $now_level_id && !$flat_grade) {
                        $real_amount = round($now_bonus * $item->user->level->flat_tp, 2);
                        Account::bonusEntry($item->uid, $real_amount, '平级收益', $uid, 3);
                        $flat_grade++;
                    }
                }
            }

        } catch (\Exception $e) {

            return $e->getMessage();
        }

        return true;
    }
}